package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.*;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.DishVO;
import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    WeChatProperties weChatProperties;
    @Autowired
    UserMapper userMapper;

    @Override
    public User login(UserLoginDTO dto) {
        String code = dto.getCode();
        String appid = weChatProperties.getAppid();
        String secret = weChatProperties.getSecret();

        HashMap<String, String> map = new HashMap<>();
        map.put("appid", appid);
        map.put("secret", secret);
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");

        String json = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", map);

        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        User user = userMapper.getUserByOpenid(openid);
        if (user == null) {
            user = User.builder().openid(openid).createTime(LocalDateTime.now()).build();
            userMapper.saveUser(user);
        }

        return user;
    }

    @Override
    public List<SetmealDish> userSetmealGetById(Long id) {
        List<SetmealDish> setmeal = userMapper.userSetmealGetById(id);
        return setmeal;
    }

    @Override
    public List<Setmeal> userSetmealList(Integer categoryId) {
        List<Setmeal> setmeals = userMapper.userSetmealList(categoryId);
        return setmeals;
    }

    @Override
    public List<DishVO> UserDishQuery(Dish dish) {
        List<DishVO> list = userMapper.UserDishQuery(dish);
        return list;
    }

    @Override
    public List<Category> categoryPageQuery(Integer type) {
        List<Category> category = userMapper.categoryPageQuery(type);
        return category;
    }
}
